package com.gaohe.interceptor;

import com.alibaba.fastjson.JSON;
import com.gaohe.common.BaseContext;
import com.gaohe.common.PathMatcher;
import com.gaohe.common.R;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
//拦截器需要配置拦截
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.白名单资源放行
        //用户的访问路径
        String requestURI = request.getRequestURI();
        boolean check = PathMatcher.check(requestURI);
        if(check){
            log.info("白名单放行：{}",requestURI);
            return true;
        }
        //2.已登录放行
//        HttpSession session = request.getSession();
//        Object user = session.getAttribute("user");
        //2.1从请求头获取auth
        String auth = request.getHeader("auth");
        Object userId=null;
        if(!StringUtils.isEmpty(auth)){
            userId= redisTemplate.opsForValue().get("auth" + auth);
        }
        if(!StringUtils.isEmpty(userId)){
            log.info("已登录放行：{}",requestURI);
            //把用户ID存入线程空间
            BaseContext.setCurrentId((Long)userId);
            return true;
        }
        //权限不够：权限处理
        //3.拦截并响应信息
        response.setStatus(401);//设置状态码
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return false;

    }
}
